package com.miaosha.ms_03.exception;

import com.miaosha.ms_03.result.CodeMsg;
import com.miaosha.ms_03.result.Result;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Description //全局异常 处理拦截
 * @Author Administrator
 * @DATE 2020/9/17 23:27
 **/
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    //对 Exception 进行拦截
    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(Exception e) {
        //对于全局异常的处理
        e.printStackTrace();
        if (e instanceof GlobalException) {
            GlobalException globalException = (GlobalException) e;
            return Result.error(globalException.getCodeMsg());
        } else if (e instanceof BindException) {
            //对于绑定异常的处理
            BindException bindException = (BindException) e;
            List<ObjectError> allErrors = bindException.getAllErrors();
            if (!CollectionUtils.isEmpty(allErrors)) {
                ObjectError obj = allErrors.get(0);
                String message = obj.getDefaultMessage();
                CodeMsg codeMsg = CodeMsg.fillArgs(message);
                return Result.error(codeMsg);
            }
        }
        return Result.error(CodeMsg.SERVER_ERR);
    }
}
